package advanced.io;

import java.io.*;
import java.net.URL;

/**
 * 转换流
 * <p>
 * <p>
 * InputstreamReader outputstreamwriter
 * <p>
 * 1. 以字符流的形式操作字节流(纯文本的)
 * 2,. 指定字符集
 */
public class L_TransformStream {
    public static void main(String[] args) {
        String target = "C:\\Users\\DMLYS\\Documents\\prepare_for_work\\pfw\\java_l\\src\\main\\java\\advanced\\io" + "/baidu.html";
        dowloadURL("http://www.baidu.com", target);

    }

    /**
     * 缓冲字符流的输入与输出
     */
    public static void test1() {
        //操作System.in 和System.out
        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader bufferedReader = new BufferedReader(isr);
        OutputStreamWriter osw = new OutputStreamWriter(System.out);
        BufferedWriter bufferedWriter = new BufferedWriter(osw);

        try (bufferedReader; bufferedWriter) {
            //循环读取键盘输入的内容, 将他保存
            String msg = "";
            while (!msg.equals("exit")) {
                msg = bufferedReader.readLine();
                bufferedWriter.write(msg);
                bufferedWriter.newLine();
                bufferedWriter.flush();
            }

        } catch (Exception e) {
            System.out.println("操作异常");
            e.printStackTrace();
        }

    }

    public static void dowloadURL(String url, String dest) {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(url).openStream(), "UTF-8"));
             BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dest, false)));

        ) {
            String line;
            while ((line = reader.readLine()) != null) {
                writer.write(line);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
